import { Component, Vue, Inject, Prop, Watch, Ref } from 'vue-property-decorator';
import { numeric, required, minLength, maxLength } from 'vuelidate/lib/validators';

import CommonTableService from '../../modelConfig//common-table/common-table.service';
import { ICommonTable } from '@/shared/model/modelConfig/common-table.model';

import DataDictionaryService from '../../settings//data-dictionary/data-dictionary.service';
import { IDataDictionary } from '@/shared/model/settings/data-dictionary.model';

import { ICommonTableRelationship, CommonTableRelationship } from '@/shared/model/modelConfig/common-table-relationship.model';
import CommonTableRelationshipService from './common-table-relationship.service';

const validations: any = {
  commonTableRelationship: {
    id: {},
    name: {
      required,
      maxLength: maxLength(100),
    },
    relationshipType: {
      required,
    },
    sourceType: {
      required,
    },
    otherEntityField: {
      maxLength: maxLength(100),
    },
    otherEntityName: {
      required,
      maxLength: maxLength(100),
    },
    relationshipName: {
      required,
      maxLength: maxLength(100),
    },
    otherEntityRelationshipName: {
      maxLength: maxLength(100),
    },
    columnWidth: {},
    order: {},
    fixed: {},
    editInList: {},
    enableFilter: {},
    hideInList: {},
    hideInForm: {},
    searchForm: {},
    system: {},
    fontColor: {
      maxLength: maxLength(80),
    },
    backgroundColor: {
      maxLength: maxLength(80),
    },
    help: {
      maxLength: maxLength(200),
    },
    ownerSide: {},
    dataName: {
      required,
      maxLength: maxLength(100),
    },
    webComponentType: {
      maxLength: maxLength(100),
    },
    otherEntityIsTree: {},
    showInFilterTree: {},
    dataDictionaryCode: {
      maxLength: maxLength(100),
    },
    clientReadOnly: {},
    endUsed: {},
    options: {},
  },
};

@Component({
  validations,
  components: {},
})
export default class CommonTableRelationshipUpdateTemplate extends Vue {
  // jhipster-pro-please-regenerate-this-file 如果您修改了此文件，并且不希望重新生成代码时被覆盖，请删除本行！！!

  @Inject('commonTableRelationshipService') private commonTableRelationshipService: () => CommonTableRelationshipService;
  public commonTableRelationship: ICommonTableRelationship = new CommonTableRelationship();

  @Inject('commonTableService') private commonTableService: () => CommonTableService;

  public commonTables: ICommonTable[] = [];

  @Inject('dataDictionaryService') private dataDictionaryService: () => DataDictionaryService;

  public dataDictionaries: IDataDictionary[] = [];
  public isSaving = false;
  public loading = false;
  @Ref('updateForm') readonly updateForm: any;
  public formJsonData = {
    list: [],
    config: {
      layout: 'horizontal',
      labelCol: { span: 4 },
      wrapperCol: { span: 18 },
      hideRequiredMark: false,
      customStyle: '',
    },
  };
  public dataFormContent = [];
  @Prop(Number) commonTableRelationshipId;
  @Prop(Number) commonTableId;
  @Prop(Boolean) showInModal;
  public dataContent = [];

  beforeRouteEnter(to, from, next) {
    next(vm => {
      vm.initRelationships();
      if (to.params.commonTableRelationshipId) {
        vm.retrieveCommonTableRelationship(to.params.commonTableRelationshipId);
      }
    });
  }
  created(): void {
    this.initRelationships();
  }

  public mounted(): void {}

  public save(): void {
    this.updateForm
      .getData()
      .then(values => {
        Object.assign(this.commonTableRelationship, values);
        this.isSaving = true;
        if (this.commonTableRelationship.id) {
          this.commonTableRelationshipService()
            .update(this.commonTableRelationship)
            .then(param => {
              this.isSaving = false;
              const message = this.$t('jhipsterApp.modelConfigCommonTableRelationship.updated', { param: param.id }).toString();
              this.$message.info(message);
              if (this.showInModal) {
                this.$emit('cancel', true);
              } else {
                this.$router.go(-1);
              }
            });
        } else {
          this.commonTableRelationshipService()
            .create(this.commonTableRelationship)
            .then(param => {
              this.isSaving = false;
              const message = this.$t('jhipsterApp.modelConfigCommonTableRelationship.created', { param: param.id }).toString();
              this.$message.success(message);
              if (this.showInModal) {
                this.$emit('cancel', true);
              } else {
                this.$router.go(-1);
              }
            });
        }
      })
      .catch(() => {
        console.log('验证未通过，获取失败');
      });
  }

  @Watch('commonTableRelationshipId', { immediate: true })
  public retrieveCommonTableRelationship(commonTableRelationshipId): void {
    this.commonTableRelationshipService()
      .find(commonTableRelationshipId)
      .then(res => {
        this.commonTableRelationship = res;
      });
  }

  public previousState(): void {
    if (this.showInModal) {
      this.$emit('cancel', false);
    } else {
      this.$router.go(-1);
    }
  }

  public initRelationships(): void {
    this.commonTableService()
      .retrieve()
      .then(res => {
        this.commonTables = res.data;
      });
    this.dataDictionaryService()
      .tree()
      .then(res => {
        this.dataDictionaries = res.data;
      });
    this.commonTableService()
      .retrieve()
      .then(res => {
        this.commonTables = res.data;
      });
    this.commonTableService()
      .retrieve()
      .then(res => {
        this.commonTables = res.data;
      });
  }

  // 有一问题要注意，我不能选择已经是我下级的节点做我的上级节点。
  public toTreeNode(items: any, valueFieldName: string, labelFieldName: string, currentId?: any, disabledParent: boolean = false) {
    const nzTreeNode = [];
    if (!items) {
      return nzTreeNode;
    }
    items.forEach(item => {
      let disabledChildren = false;
      const option = {
        value: item[valueFieldName],
        label: item[labelFieldName],
        disabled: disabledParent, // 树形关系中自己不能选择自己做为上级对象。
        children: undefined,
      };
      if (item[valueFieldName] === currentId) {
        option.disabled = true;
        disabledChildren = true;
      }
      if (item.children && item.children.length > 0) {
        option.children = this.toTreeNode(item.children, valueFieldName, labelFieldName, currentId, disabledChildren);
      }
      nzTreeNode.push(option);
    });
    console.log(nzTreeNode);
    return nzTreeNode;
  }
}
